package com.kylin.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三：实现callable接口

/**
 * 1。可以定义返回值
 * 2.可以抛出异常
 */
public class TestThreadCallable implements Callable<Boolean> {

    private String url;//网络图片地址
    private String name;//保存的文件名

    public TestThreadCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownloader1 webDownloader1 = new WebDownloader1();
        webDownloader1.downloader(url, name);
        System.out.println("下载了文件名为" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestThreadCallable t1 = new TestThreadCallable("https://cdn.jsdelivr.net/gh/kylincw/img/img/%E5%AE%87%E8%88%AA%E5%91%98.png", "1.png");
        TestThreadCallable t2 = new TestThreadCallable("https://cdn.jsdelivr.net/gh/kylincw/img/img/%E5%AE%87%E8%88%AA%E5%91%98.png", "2.png");
        TestThreadCallable t3 = new TestThreadCallable("https://cdn.jsdelivr.net/gh/kylincw/img/img/%E5%AE%87%E8%88%AA%E5%91%98.png", "3.png");

        //创建执行服务
        ExecutorService es = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = es.submit(t1);
        Future<Boolean> r2 = es.submit(t2);
        Future<Boolean> r3 = es.submit(t3);

        //获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();

        //关闭服务
        es.shutdown();
    }
}

//下载器
class WebDownloader1 {
    //下载方法
    public void downloader(String url, String name) {

        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}

